package com.yugongyun.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public final class MyBatisUtil {

    private static final SqlSessionFactory FACTORY;


    private static final ThreadLocal<SqlSession> TL = new ThreadLocal<>();

    static {
        try (InputStream is = Resources.getResourceAsStream("mybatis-config.xml")) {
            FACTORY = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new ExceptionInInitializerError("初始化 SqlSessionFactory 失败：" + e.getMessage());
        }
    }

    public static SqlSession getSession() {
        SqlSession session = TL.get();
        if (session == null) {
            session = FACTORY.openSession(false); // 手动提交事务
            TL.set(session);
        }
        return session;
    }


    public static void closeSession() {
        SqlSession session = TL.get();
        if (session != null) {
            session.commit();   // 业务层无异常时提交
            session.close();
            TL.remove();        // 防止内存泄漏
        }
    }


    public static void rollback() {
        SqlSession session = TL.get();
        if (session != null) {
            session.rollback();
        }
    }


    public static <T> T getMapper(Class<T> mapperClass) {
        return getSession().getMapper(mapperClass);
    }

    private MyBatisUtil() {}
}